const Logger = require('../lib/logger')
const ip2region = require('../lib/utils/ip2region')

let searcher = null

function onModuleInit() {
  const { config } = ip2region

  if (!config) {
    Logger.warn(
      'The ip2region configuration is missing or incomplete. Please check your configuration files and ensure that all required ip2region settings, including "xdbPath" and "mode", are correctly specified.',
      'Ip2regionService'
    )
    return
  }

  switch (config.mode) {
    case ip2region.SearchMode.File:
      searcher = ip2region.newWithFileOnly(config.xdbPath)
      Logger.log(`Initializing ip2region with File mode using database path: ${config.xdbPath}`, 'Ip2regionService')
      break
    case ip2region.SearchMode.VectorIndex:
      const vectorIndex = ip2region.loadVectorIndexFromFile(config.xdbPath)
      searcher = ip2region.newWithVectorIndex(config.xdbPath, vectorIndex)
      Logger.log(`Initializing ip2region with VectorIndex mode using database path: ${config.xdbPath}`, 'Ip2regionService')
      break
    case ip2region.SearchMode.Full:
      const buffer = ip2region.loadContentFromFile(config.xdbPath)
      searcher = ip2region.newWithBuffer(buffer)
      Logger.log(`Initializing ip2region with Full mode using database path: ${config.xdbPath}`, 'Ip2regionService')
      break
    default:
      Logger.warn(`Unsupported search mode: ${config.mode}`, '', 'Ip2regionService')
    // 非必需异常,有些系统不需要ip2region
    // throw new Error(`Unsupported search mode: ${config.mode}`);
  }
}

function getSearcher() {
  if (!searcher) {
    onModuleInit()
  }
  return searcher
}

module.exports = {
  getSearcher
}
